package com.dingyuhang.service.impl;


import com.dingyuhang.bean.User;
import com.dingyuhang.common.TiebaException;
import com.dingyuhang.mapper.UserMapper;
import com.dingyuhang.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.List;
import java.util.UUID;

@Service
@Transactional
public class UserServiceImpl implements UserService {
	
	@Autowired
	private UserMapper userMapper;

	/**
	 *  首页--最新用户
	 */
	@Override
	public PageInfo<User> selectUsers(Integer pageNum) {
		  PageHelper.startPage(pageNum, 5);
		  List<User> users =userMapper.selectUsers();
		return new PageInfo<>(users);
	}

	@Override
	public void insertUser(User user, MultipartFile file) {
		 try {
			 if(null !=file && file.getSize()>0) {
					String path="c:\\img";
					String fileName=UUID.randomUUID().toString()+file.getOriginalFilename();
					File file2 = new File(path,fileName);
					file.transferTo(file2);
					user.setImgurl("/img/"+fileName);
				}
			 userMapper.insertUser(user);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
	}
	
	
	@Override
	public User login(User user) {
		    if (user.getUserName() == null || user.getUserName().length() == 0) {
	            throw new TiebaException("用户名不能空");
	        }
		    
	        User selectUser = userMapper.selectByUsername(user.getUserName());//查询用户名
	        
	        if (selectUser == null) {
	            throw new TiebaException("用户名或密码错误");
	        }
	        if (user.getPassword() == null || !user.getPassword().equals(selectUser.getPassword())) {
	            throw new TiebaException("密码错误");
	        }
		return selectUser;
	}
	
	
	
	@Override
	public void updateUser(User user, MultipartFile file) {
		 try {
			 if(null !=file && file.getSize()>0) {
					String path="c:\\img";
					String fileName=UUID.randomUUID().toString()+file.getOriginalFilename();
					File file2 = new File(path,fileName);
					file.transferTo(file2);
					user.setImgurl("/img/"+fileName);
				}
			 userMapper.updateUser(user);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	@Override
	public User getUserById(Integer id) {
		return userMapper.getUserById(id);
	}
	
	
	@Override
	public User selectUserById(Integer id) {
		return userMapper.selectUserById(id);
	}

	
	@Override
	public int count(User user) {
		return userMapper.count(user);
	}
}
